<?php
// +----------------------------------------------------------------------
// | 萤火商城系统 [ 致力于通过产品和服务，帮助商家高效化开拓市场 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2021 https://www.yiovo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件，不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 萤火科技 <admin@yiovo.com>
// +----------------------------------------------------------------------
declare (strict_types = 1);

namespace app\store\model\store;

use app\common\enum\user\balanceLog\Scene as SceneEnum;
use app\common\model\store\Shop as ShopModel;
use app\common\service\qrcode\Shop as ShopQRcode;
use app\store\model\ding\ShopImages as ShopImagesModel;
use app\store\model\ding\ShopAdvImages as ShopAdvImagesModel;
use app\store\model\store\BalanceLog as BalanceLogModel;
use app\store\model\store\ShopCaixiRel as ShopCaixiRelModel;
use app\store\model\store\ShopTypeRel as ShopTypeRelModel;
use app\store\service\store\User as StoreUserService;
use Lvht\GeoHash;
use think\facade\Db;

/**
 * 商家门店模型
 * Class Shop
 * @package app\store\model\store
 */
class Shop extends ShopModel
{
    public function getListDaili(array $param = [])
    {
        return $this->with(['logoImage', 'daili'])
            ->withoutField(['content'])
            ->where($this->getFilter($param))
            ->where('is_delete', '=', 0)
            ->where('daili_id', '>', 0)
            ->order(['sort' => 'asc', $this->getPk()])
            ->paginate(15)->each(function ($item, $key) {
            $time      = strtotime(Date('Y-m-01'));
            $ids       = Db::name('store_shop_order')->where('shop_id', $item['shop_id'])->field('order_id')->select()->toArray();
            $ids       = array_column($ids, 'order_id');
            $month_ids = Db::name('store_shop_order')
                ->where('create_time', '>', $time)->where('shop_id', $item['shop_id'])->field('order_id')->select()->toArray();
            $month_ids                  = array_column($month_ids, 'order_id');
            $item['total_amount']       = Db::name('order')->where('order_id', 'in', $ids)->sum('pay_price');
            $item['total_amount_month'] = Db::name('order')->where('order_id', 'in', $month_ids)->sum('pay_price');
            return $item;
        });
    }
    /**
     * 获取列表数据
     * @param array $param
     * @return \think\Paginator
     * @throws \think\db\exception\DbException
     */
    public function getList(array $param = [])
    {
        $sort = ['sort' => 'asc', $this->getPk()];
        if (isset($param['sort'])) {
            if ($param['sort'] == 1) {
                $sort = ['end_date' => 'asc', 'status' => 'desc'];
            }
            if ($param['sort'] == 2) {
                $sort = ['end_date' => 'desc'];
            }
        }
        return $this->with(['logoImage', 'vrImage'])
            ->withoutField(['content'])
            ->where($this->getFilter($param))
            ->where('is_delete', '=', 0)
            ->order($sort)

            ->paginate(15)->each(function ($item, $key) {
            $time      = strtotime(Date('Y-m-01'));
            $ids       = Db::name('store_shop_order')->where('shop_id', $item['shop_id'])->field('order_id')->select()->toArray();
            $ids       = array_column($ids, 'order_id');
            $month_ids = Db::name('store_shop_order')
                ->where('create_time', '>', $time)->where('shop_id', $item['shop_id'])->field('order_id')->select()->toArray();
            $month_ids                  = array_column($month_ids, 'order_id');
            $item['total_amount']       = Db::name('order')->where('order_id', 'in', $ids)->sum('pay_price');
            $item['total_amount_month'] = Db::name('order')->where('order_id', 'in', $month_ids)->sum('pay_price');
            return $item;
        });
    }
    public function getListShuju(array $param = [])
    {
        $sort = ['sort' => 'asc', $this->getPk()];

        return $this->with(['logoImage'])
            ->withoutField(['content'])
            ->where($this->getFilter($param))
            ->where('is_delete', '=', 0)
            ->order($sort)
            ->paginate(15)->each(function ($item, $key) {

            $item['poster_count'] = Db::name('ding_order')
                ->where('shop_id', $item['shop_id'])->count();
            $item['member_count'] = Db::name('ding_clerk_member')
                ->where('shop_id', $item['shop_id'])->where('is_delete', 0)->where('clerk_id',0)->count();
            $item['clerk_count'] = Db::name('store_shop_clerk')->where('shop_id', $item['shop_id'])->where('is_delete', 0)->count();

            return $item;
        });
    }
    public static function getListAll(array $param = [])
    {
        $model = new static;
        return $model
            ->withoutField(['content'])
            ->where('is_delete', '=', 0)
            ->select();
    }
    /**
     * 获取所有门店列表
     * @param array $param
     * @return \think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getAll(array $param = [])
    {
        $model = new static;
        return $model->with(['logoImage'])
            ->withoutField(['content'])
            ->where($model->getFilter($param))
            ->where('is_delete', '=', 0)
            ->select();
    }

    /**
     * 设置列表查询条件
     * @param array $param
     * @return array
     */
    private function getFilter(array $param = []): array
    {
        // 默认查询参数
        $params = $this->setQueryDefaultValue($param, [
            'search'  => '', // 搜索关键词: 门店名称/联系人/电话
            'isCheck' => -1, // 是否支持自提核销(0否 1支持)
            'status'  => '', // 门店状态
        ]);
        // 检索查询条件
        $filter = [];
        // 是否支持自提核销
        $params['isCheck'] > -1 && $filter[] = ['is_check', '=', (int) $params['isCheck']];
        // 搜索关键词
        ! empty($params['search']) && $filter[] = ['shop_name|linkman|phone', 'like', "%{$params['search']}%"];
        // 门店状态
        is_numeric($params['status']) && $filter[] = ['status', '=', (int) $params['status']];

        //查询是否代理
        // 当前操作人用户名
        $storeUserName = StoreUserService::getLoginInfo()['user']['user_name'];
        $daili         = Db::name('ding_daili')->where('mobile', $storeUserName)->find();
        if ($daili) {
            $filter[] = ['daili_id', '=', $daili['clerk_id']];
        }

        $storeUser = StoreUserService::getLoginInfo()['user'];
        if ($storeUser['shop_id'] > 0) {
            $filter[] = ['shop_id', '=', $storeUser['shop_id']];
        }

        return $filter;
    }
    /**
     * 用户充值
     * @param string $target 充值类型
     * @param array $data 表单数据
     * @return bool
     */
    public function recharge(string $target, array $data)
    {
        // 当前操作人用户名
        $storeUserName = StoreUserService::getLoginInfo()['user']['user_name'];
        return $this->rechargeToBalance($storeUserName, $data['balance']);

    }

    /**
     * 用户充值：余额
     * @param string $storeUserName
     * @param array $data
     * @return bool
     */
    private function rechargeToBalance(string $storeUserName, array $data)
    {
        if (! isset($data['money']) || $data['money'] === '' || $data['money'] < 0) {
            $this->error = '请输入正确的金额';
            return false;
        }
        // 判断充值方式，计算最终金额
        if ($data['mode'] === 'inc') {
            $diffMoney = $data['money'];
        } elseif ($data['mode'] === 'dec') {
            $diffMoney = -$data['money'];
        } else {
            $diffMoney = helper::bcsub($data['money'], $this['balance']);
        }
        // 更新记录
        $this->transaction(function () use ($storeUserName, $data, $diffMoney) {
            // 更新账户余额
            static::setIncBalance((int) $this['shop_id'], (float) $diffMoney);
            // 新增余额变动记录
            BalanceLogModel::add(SceneEnum::ADMIN, [
                'shop_id' => $this['shop_id'],
                'money'   => (float) $diffMoney,
                'mobiles'   =>'',
                'remark'  => $data['remark'],
            ], [$storeUserName]);
        });
        return true;
    }
    /**
     * 新增记录
     * @param array $data
     * @return bool
     */
    public function add(array $data)
    {
        if (! $this->validateForm($data)) {
            return false;
        }

        $this->save($this->createData($data));

        ShopCaixiRelModel::add((int) $this['shop_id'], $data['caixi']);
        ShopTypeRelModel::add((int) $this['shop_id'], $data['types']);
        ShopImagesModel::add((int) $this['shop_id'], $data['imagesIds']);
        ShopAdvImagesModel::add((int) $this['shop_id'], $data['imagesAdvIds']);
        // 创建二维码
        $Qrcode = new ShopQRcode((int) $this['shop_id'], 'MP-WEIXIN');
        $Qrcode->getImage();
        return true;
    }

    /**
     * 编辑记录
     * @param array $data
     * @return false|int
     */
    public function edit(array $data)
    {
        if (! $this->validateForm($data)) {
            return false;
        }

        Db::name('ding_shop_type_rel')->where('shop_id', (int) $this['shop_id'])->delete();
        Db::name('ding_shop_foods_rel')->where('shop_id', (int) $this['shop_id'])->delete();
        Db::name('ding_shop_images')->where('shop_id', (int) $this['shop_id'])->delete();
        Db::name('ding_shop_adv_images')->where('shop_id', (int) $this['shop_id'])->delete();

        // 创建二维码
        $Qrcode = new ShopQRcode((int) $this['shop_id'], 'MP-WEIXIN');
        $Qrcode->getImage();
        ShopCaixiRelModel::add((int) $this['shop_id'], $data['caixi']);
        ShopTypeRelModel::add((int) $this['shop_id'], $data['types']);
        ShopImagesModel::add((int) $this['shop_id'], $data['imagesIds']);
        ShopAdvImagesModel::add((int) $this['shop_id'], $data['imagesAdvIds']);

        return $this->save($this->createData($data)) !== false;
    }

    /**
     * 软删除
     * @return false|int
     */
    public function setDelete()
    {
        return $this->save(['is_delete' => 1]);
    }

    /**
     * 创建数据
     * @param array $data
     * @return array
     */
    private function createData(array $data)
    {
        // 格式化坐标信息
        $coordinate        = explode(',', $data['coordinate']);
        $data['latitude']  = $coordinate[0];
        $data['longitude'] = $coordinate[1];

        $data['end_date'] = strtotime($data['end_date']);

        //查询是否代理
        // 当前操作人用户名
        $storeUserName = StoreUserService::getLoginInfo()['user']['user_name'];
        $daili         = Db::name('ding_daili')->where('mobile', $storeUserName)->find();
        if ($daili) {
            $data['daili_id'] = $daili['clerk_id'];
        }

        // 生成geohash
        $data['geohash'] = (new Geohash)->encode($data['longitude'], $data['latitude']);
        // 省市区ID
        list($data['province_id'], $data['city_id'], $data['region_id']) = $data['cascader'];

        $data['city'] = Db::name('region')->where('id', $data['city_id'])->value('name');
        // 当前商城ID
        $data['store_id'] = self::$storeId;
        return $data;
    }

    /**
     * 表单验证
     * @param array $data
     * @return bool
     */
    private function validateForm(array $data)
    {
        if (! isset($data['logo_image_id']) || empty($data['logo_image_id'])) {
            $this->error = '请选择门店logo';
            return false;
        }
        return true;
    }
}
